<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        width="50%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem :label="t('region.apply.user_id')" type="remoteSelect" v-model="baTable.form.items!.user_id" prop="user_id" :input-attr="{ pk: 'xxz_user.id', field: 'nickname', 'remote-url': '/admin/user.User/index' }" :placeholder="t('Please select field', { field: t('region.apply.user_id') })" />
                    <FormItem :label="t('region.apply.agent_type')" type="radio" v-model="baTable.form.items!.agent_type" prop="agent_type" :data="{ content: { area_agent: t('region.apply.agent_type area_agent'), city_agent: t('region.apply.agent_type city_agent'), province_agent: t('region.apply.agent_type province_agent') } }" :placeholder="t('Please select field', { field: t('region.apply.agent_type') })" />
                    <!-- 统一的级联选择器，根据代理类型显示不同级别 -->
                    <FormItem 
                        :key="`cascade-${baTable.form.items?.agent_type || 'default'}`"
                        :label="getAreaLabel()" 
                        type="city" 
                        v-model="cascadeArea" 
                        prop="cascade_area" 
                        :data="{ level: getAreaLevel() }" 
                        :placeholder="t('Please select field', { field: getAreaLabel() })" 
                    />
                    <FormItem :label="t('region.apply.apply_reason')" type="textarea" v-model="baTable.form.items!.apply_reason" prop="apply_reason" :input-attr="{ rows: 3 }" @keyup.enter.stop="" @keyup.ctrl.enter="baTable.onSubmit(formRef)" :placeholder="t('Please input field', { field: t('region.apply.apply_reason') })" />
                    <FormItem :label="t('region.apply.reject_reason')" type="textarea" v-model="baTable.form.items!.reject_reason" prop="reject_reason" :input-attr="{ rows: 3 }" @keyup.enter.stop="" @keyup.ctrl.enter="baTable.onSubmit(formRef)" :placeholder="t('Please input field', { field: t('region.apply.reject_reason') })" />
                    <FormItem :label="t('region.apply.files')" type="files" v-model="baTable.form.items!.files" prop="files" />
                    <FormItem :label="t('region.apply.review_status')" type="radio" v-model="baTable.form.items!.review_status" prop="review_status" :data="{ content: { '0': t('region.apply.review_status 0'), '1': t('region.apply.review_status 1'), '2': t('region.apply.review_status 2') } }" :placeholder="t('Please select field', { field: t('region.apply.review_status') })" />
                    <FormItem :label="t('region.apply.status')" type="switch" v-model="baTable.form.items!.status" prop="status" :data="{ content: { '0': t('region.apply.status 0'), '1': t('region.apply.status 1') } }" />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, reactive, ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

// 统一的级联选择器
const cascadeArea = computed({
    get: () => {
        if (baTable.form.items?.cascade_area) {
            return baTable.form.items.cascade_area
        }
        return []
    },
    set: (value: number[]) => {
        if (baTable.form.items) {
            baTable.form.items.cascade_area = value
        }
    }
})

// 根据代理类型获取区域标签
const getAreaLabel = () => {
    const agentType = baTable.form.items?.agent_type
    if (agentType === 'province_agent') {
        return t('region.apply.province')
    } else if (agentType === 'city_agent') {
        return t('region.apply.city')
    } else if (agentType === 'area_agent') {
        return t('region.apply.area')
    }
    return t('region.apply.area')
}

// 根据代理类型获取区域级别
const getAreaLevel = () => {
    const agentType = baTable.form.items?.agent_type
    let level = 3  // 默认返回3级
    if (agentType === 'province_agent') {
        level = 1  // 省级代理：只需要省级（1级）
    } else if (agentType === 'city_agent') {
        level = 2  // 市级代理：需要省市级（2级）
    } else if (agentType === 'area_agent') {
        level = 3  // 区级代理：需要省市区级（3级）
    }
    console.log('代理类型:', agentType, '级别:', level)
    return level
}

// 监听代理类型变化，清空级联选择器的值
watch(
    () => baTable.form.items?.agent_type,
    (newType, oldType) => {
        if (newType !== oldType && baTable.form.items) {
            // 清空级联选择器的值
            baTable.form.items.cascade_area = []
            console.log('代理类型已改变，清空级联选择器值')
        }
    }
)

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    update_time: [buildValidatorData({ name: 'date', title: t('region.apply.update_time') })],
    create_time: [buildValidatorData({ name: 'date', title: t('region.apply.create_time') })],
})
</script>

<style scoped lang="scss"></style>
